using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.Rendering.Universal;

namespace CNGraphi.U6URP
{
    /// <summary>
    /// 径向模糊
    /// <para>作者：CN.Graphi</para>
    /// </summary>
    [VolumeComponentMenu("G Post-processing/Blur/Radial")]
    public class RadialBlur : GPostProcess
    {
        #region 参数
        public Vector2Parameter Center = new Vector2Parameter(new Vector2(0.5f, 0.5f), true);
        public ClampedIntParameter Downsample = new ClampedIntParameter(2, 1, 10, true);
        public ClampedIntParameter Iteration = new ClampedIntParameter(16, 2, 64, true);
        public FloatRangeParameter FilterRange = new FloatRangeParameter(Vector2.zero, 0f, 1f, true);
        public MinFloatParameter Intensity = new MinFloatParameter(0.0f, 0.0f, true);
        #endregion

        public override bool IsActive() => mMaterial != null && Intensity != 0.0f;

        TextureHandle temp0;
        //TextureHandle temp1;
        Vector4 param;

        internal override void OnTextureCreate(RenderGraph renderGraph, ContextContainer frameData)
        {
            if (mMaterial == null) { return; }

            UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();
            var desc = cameraData.cameraTargetDescriptor;

            int downValue = Downsample.value;
            int tw = Mathf.Max(1, desc.width >> downValue);
            int th = Mathf.Max(1, desc.height >> downValue);

            desc.width = tw;
            desc.height = th;
            desc.depthBufferBits = 0;

            temp0 = UniversalRenderer.CreateRenderGraphTexture(renderGraph, desc, "RadialBlur_Vertical", false, FilterMode.Bilinear, TextureWrapMode.Clamp);
            //temp1 = UniversalRenderer.CreateRenderGraphTexture(renderGraph, desc, "RadialBlur_Horizontal", false, FilterMode.Bilinear, TextureWrapMode.Clamp);
        }

        internal override void OnTextureUseCommit(IUnsafeRenderGraphBuilder builder)
        {
            if (mMaterial == null) { return; }

            builder.UseTexture(temp0);
            //builder.UseTexture(temp1);
        }

        internal override void OnRender(CommandBuffer cmd, PostProcessPassData passData, TextureHandle src, TextureHandle dst)
        {
            if (mMaterial == null) { return; }

            param.Set(Center.value.x, Center.value.y, Intensity.value, Iteration.value);
            mMaterial.SetVector("_Params", param);
            mMaterial.SetVector("_FilterRange", FilterRange.value);

            Draw(cmd, src, temp0, 0);
            Draw(cmd, temp0, dst);
        }

        protected override void OnDispose()
        {
        }



    }
}